import { Module } from 'vuex'
import { IRootState } from '@/store/types'
import { ISystemState } from './types'

import {
  getPageListData,
  deletePageData,
  createPageData,
  editPageData
} from '@/service/main/system/system'

import { ElMessageBox } from 'element-plus'

const systemModule: Module<ISystemState, IRootState> = {
  namespaced: true,
  state() {
    return {
      userList: [],
      userCount: 0,
      roleList: [],
      roleCount: 0,
      menuList: [],
      menuCount: 0,
      permissionList: [],
      permissionCount: 0,
      requestsList: {},
      requestList: [],
      requestCount: 0,
      recordList: [],
      recordCount: 0
    }
  },
  mutations: {
    changeUserList(state, userList: any[]) {
      state.userList = userList
    },
    changeUserCount(state, userCount: number) {
      state.userCount = userCount
    },
    changeRoleList(state, list: any[]) {
      state.roleList = list
    },
    changeRoleCount(state, count: number) {
      state.roleCount = count
    },
    changeMenuList(state, list: any[]) {
      state.menuList = list
    },
    changeMenuCount(state, count: number) {
      state.menuCount = count
    },
    changePermissionList(state, list: any[]) {
      state.permissionList = list
    },
    changePermissionCount(state, count: number) {
      state.permissionCount = count
    },
    changeRequetsList(state, list: any) {
      state.requestsList = list
    },
    changeRequestList(state, list: any[]) {
      state.requestList = list
    },
    changeRequestCount(state, count: number) {
      state.requestCount = count
    },
    changeRecordList(state, list: any[]) {
      state.recordList = list
    },
    changeRecordCount(state, count: number) {
      state.recordCount = count
    }
  },
  getters: {
    pageListData(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}List`]
      }
    },
    pageListCount(state) {
      return (pageName: string) => {
        return (state as any)[`${pageName}Count`]
      }
    }
  },
  actions: {
    async getPageListAction({ commit }, payload: any) {
      // 1.获取pageUrl
      const pageName = payload.pageName
      // const pageUrl = `/${pageName}s/list`
      const pageUrl = `/user/get_${pageName}_list`
      // 2.对页面发送请求
      const pageResult = await getPageListData(pageUrl, payload.queryInfo)
      console.log('111112')
      console.log(pageResult.data)
      // 3.将数据存储到state中
      const { list, totalCount } = pageResult.data

      const changePageName =
        pageName.slice(0, 1).toUpperCase() + pageName.slice(1)
      commit(`change${changePageName}List`, list)
      commit(`change${changePageName}Count`, totalCount)
    },

    async getPermissionListAction({ commit }, payload: any) {
      // 1.获取pageUrl
      const pageName = payload.pageName
      const pageUrl = `/user/get_${pageName}s`
      // 2.对页面发送请求
      const pageResult = await getPageListData(pageUrl, payload.queryInfo)
      console.log(pageResult.data)
      // 3.将数据存储到state中
      const { request_obj, permission_list } = pageResult.data

      commit(`changePermissionList`, permission_list)
      commit(`changeRequetsList`, request_obj)
    },

    async deletePageDataAction({ dispatch }, payload: any) {
      // 1.获取pageName和id
      // pageName -> /users
      // id -> /users/id
      ElMessageBox.alert('Are you sure to delete?', 'Title', {
        confirmButtonText: 'OK',
        callback: (action: any) => {
          if (action === 'confirm') {
            const { pageName, id } = payload
            const pageUrl = `/${pageName}/del/${id}`
            // 2.调用删除网络请求
            const pageResult = deletePageData(pageUrl)
            console.log(pageResult)
            // 3.重新请求最新的数据
            dispatch('getPageListAction', {
              pageName,
              queryInfo: {
                offset: 0,
                size: 10
              }
            })
          }
          // ElMessage({
          //   type: 'info',
          //   message: `action: ${action}`
          // })
        }
      })
      console.log('111')
    },

    async createPageDataAction({ dispatch }, payload: any) {
      // 1.创建数据的请求
      const { pageName, newData } = payload
      const pageUrl = `/${pageName}/add_${pageName}`
      await createPageData(pageUrl, newData)

      // 2.请求最新的数据
      dispatch('getPageListAction', {
        pageName,
        queryInfo: {
          offset: 0,
          size: 10
        }
      })
    },

    async editPageDataAction({ dispatch }, payload: any) {
      // 1.编辑数据的请求
      const { pageName, editData, id } = payload
      // console.log(editData)
      const pageUrl = `/${pageName}/update_${pageName}/${id}`
      await editPageData(pageUrl, editData)

      // 2.请求最新的数据
      dispatch('getPageListAction', {
        pageName,
        queryInfo: {
          offset: 0,
          size: 10
        }
      })
    },

    async requestPermissionAction({ dispatch }, payload: any) {
      // 1.创建数据的请求
      const pageUrl = `/user/request_permission`
      const pageResult = await getPageListData(pageUrl, payload)
      console.log(pageResult.code)
      if (pageResult.code == 0) {
        ElMessageBox.alert(
          'Permission request was submitted successfully, please wait for approval!',
          'Message',
          {
            confirmButtonText: 'OK',
            callback: (action: any) => {
              if (action === 'confirm') {
                // 2.调用删除网络请求
                console.log(pageResult)
                // 3.重新请求最新的数据
                dispatch('getPermissionListAction', {
                  pageName: 'permission'
                })
              }
            }
          }
        )
      } else {
        ElMessageBox.alert(
          'Permission request failed, Please contact administrator: linzhong.zhang@solidigm.com',
          'Message'
        )
      }
    },
    async approvePermissionAction({ dispatch }, payload: any) {
      // 1.创建数据的请求
      const pageUrl = `/user/approve_request`
      const pageResult = await getPageListData(pageUrl, payload)
      // console.log(pageResult.code)
      if (pageResult.code == 0) {
        console.log('The permission request was approved!')
      } else {
        ElMessageBox.alert(pageResult.data, 'Message')
      }
      // dispatch('getPageListAction', {
      //   pageName: 'request',
      //   queryInfo: {
      //     offset: 0,
      //     size: 10
      //   }
      // })
    }
  }
}

export default systemModule
